//
//  HYGroupInfoVC.m
//  HYChatProject
//
//  Created by Jagtu on 2018/3/4.
//  Copyright © 2018年 erpapa. All rights reserved.
//

#import "HYGroupInfoVC.h"
#import "HYXMPPGroupManager.h"
#import "YHGroupInviteViewController.h"
#import "HYCommonSetViewController.h"
#import "HYUservCardViewController.h"
#import "HYDatabaseHandler+HY.h"
#import "HYRecentChatModel.h"
#import "HYContactsModel.h"
#import "HYXMPPManager.h"
#import "HYLoginInfo.h"
#import "HYUtils.h"
#import "APGroupImageUtil.h"
#import "HYXMPPManager.h"

@interface HYGroupInfoVC ()

@property(nonatomic,assign)BOOL isModify;
@property(nonatomic,strong)NSDictionary * roomInfo;
@property(nonatomic,assign)BOOL isSelfOwn;
@property(nonatomic,strong)NSMutableArray * groupMembers;
@property(nonatomic,strong)NSMutableArray * membersImages;
@property (nonatomic, strong) XMPPvCardTemp *vCard;

@end

@implementation HYGroupInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"群组信息";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self requestGroupMembers];
    
    __weak typeof(self) weakSelf = self;
    [[HYXMPPManager sharedInstance] getvCardFromJID:self.model.jid vCardBlock:^(XMPPvCardTemp *vCardTemp) {
        // 获取名片
        __strong typeof(weakSelf) strongSellf = weakSelf;
        strongSellf.vCard = vCardTemp;
    }];
    
    [self requestGroupHeader];
    
    [self refreshGroupInfoView];
    
    [self refreshClearView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self generateHeadImage];
}

#pragma mark -

-(void)requestGroupMembers
{
    __weak typeof(self) weakSelf = self;
    // 获取群成员
    [HYUtils showLoadingMsg:nil];
    [[HYXMPPGroupManager sharedInstance] fetchGroup:self.model.jid members:^(NSArray *jidStrList) {
        [HYUtils clearWaitingMsg];
        [weakSelf.groupMembers removeAllObjects];
        for (NSString *jidStr in jidStrList) {
            XMPPJID * jid = [XMPPJID jidWithString:jidStr];
            NSString *nickName = [[HYLoginInfo sharedInstance] nickNameForJid:jid];
            HYContactsModel * model = [[HYContactsModel alloc] init];
            model.jid = jid;
            model.nickName = nickName;
            model.isGroup = NO;
            model.sectionNum = 1;
            if ([[HYXMPPGroupManager sharedInstance] isGroupOwner:jid] ) {
                [weakSelf.groupMembers insertObject:model atIndex:0];
            }else{
                [weakSelf.groupMembers addObject:model];
            }
        }
        [weakSelf refreshData];
        
    }];
}

-(void)refreshData
{
    self.isSelfOwn = [[HYXMPPGroupManager sharedInstance] isGroupOwner:[HYXMPPManager sharedInstance].myJID];
    
    NSString * groupSubject = [self.roomInfo objectForKey:@"muc#roominfo_subject"];
    if (groupSubject) {
        UILabel * groupSubjectLabel = (UILabel *)[self.groupInfoView viewWithTag:222];
        groupSubjectLabel.text = groupSubject;
    }
    
    if (self.isSelfOwn) {
        [_delAndExitBtn setTitle:@"删除并退出" forState:UIControlStateNormal];
    }else{
        [_delAndExitBtn setTitle:@"退出群组" forState:UIControlStateNormal];
    }
    
    NSMutableArray * objects = [NSMutableArray array];
    for (HYContactsModel * member in self.groupMembers) {
        NSString * isOwn= [[HYXMPPGroupManager sharedInstance] isGroupOwner:member.jid]?@"1":@"0";
        [objects addObject:@{@"content":member.jid.full,@"type":@"member",@"isOwn":isOwn}];
    }
    if (self.isSelfOwn) {
        [objects addObject:@{@"content":@"icon_add.png",@"type":@"add"}];
        [objects addObject:@{@"content":@"icon_remove.png",@"type":@"remove"}];
    }
    
    [self refreshGroupMember:objects];
}

-(void)requestGroupHeader
{
    [[HYXMPPManager sharedInstance] getAvatarFromJID:self.model.jid avatarBlock:^(NSData *avatar) {
        if (avatar.length) {
            NSLog(@"获取群头像成功！");
            
            [[HYLoginInfo sharedInstance] saveGroupImage:[UIImage imageWithData:avatar] withJidU:self.model.jid.user];
        }
    }];
}

#pragma mark - view

-(void)createView
{
    [self.view addSubview:self.topScrollView];
    [self.topScrollView addSubview:self.groupMemberView];
    [self.view addSubview:self.groupInfoView];
    [self.view addSubview:self.clearView];
    [self.view addSubview:self.delAndExitBtn];
    
}

-(void)layoutSubviews
{
    NSInteger rowNum = (MAX((self.groupMembers?self.groupMembers.count:0)+(self.isSelfOwn?2:0), 1)-1)/5+1;
    CGFloat height = ((VERTICAL_SCREEN_WIDTH-60)/5.0-6+25 + 10) * rowNum + 20;
    
    HYLog(@"layoutSubviews topScrollView.height：%f",height);
    
    CGFloat y = 64;
    
    self.topScrollView.frame = CGRectMake(-1, y, kScreenW+2, height);
    
    self.groupMemberView.frame = CGRectMake(1, 5, kScreenW, height-5);
    
    y = y + height + 15;
    self.groupInfoView.frame = CGRectMake(-1, y, kScreenW+2, 108);
    
    y = y + 108 + 15;
    self.clearView.frame = CGRectMake(-1, y, kScreenW+2, 42);
    
    y = y + 42 + 25;
    self.delAndExitBtn.frame = CGRectMake(20, y, kScreenW-40, 44);
    
}

#pragma mark - 更新成员
-(void)refreshGroupMember:(NSArray *)members
{
    [self.groupMemberView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    HYLog(@"refreshGroupMember:%@",members);
    
    int items = 5;
    CGFloat paddingTop = 10;
    CGFloat itemW = (VERTICAL_SCREEN_WIDTH-paddingTop*(items+1))/items;
    
    int i = 0,row = 0,col = 0;
    for (NSDictionary * dic in members) {
        NSString * type = [dic objectForKey:@"type"];
        NSString * content = [dic objectForKey:@"content"];
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(paddingTop+row*(paddingTop+itemW)+3, paddingTop+col*(itemW+25+paddingTop), itemW-6, itemW-6)];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = itemW/2.0-3;
        imageView.image = [UIImage imageNamed:@"defaultHead"];
        
        [self.groupMemberView addSubview:imageView];
        
        //名称
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(paddingTop+row*(paddingTop+itemW)-3, imageView.frame.size.height+imageView.frame.origin.y, itemW+6, 25)];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor darkTextColor];
        label.font = [UIFont systemFontOfSize:12];
        [self.groupMemberView addSubview:label];
        
        i++;
        row = i%items;
        col = i/items;
        
        if ([@"member" isEqualToString:type]) {
            
            label.text = [content rangeOfString:@"@"].location!=NSNotFound?[content substringToIndex:[content rangeOfString:@"@"].location]:content;
            
            NSString * isOwn = [dic objectForKey:@"isOwn"];
            
            if ([isOwn isEqualToString:@"1"]) {
                //管理员
                UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, itemW-21, imageView.frame.size.width, 15)];
                label.textAlignment = NSTextAlignmentCenter;
                label.text = @"群主";
                label.backgroundColor = COLOR(0, 0, 0, 0.3);
                label.textColor = COLOR(247, 247, 247, 0.9);
                label.font =[UIFont systemFontOfSize:9];
                [imageView addSubview:label];
            }
            //修改为添加删除成员时，上传群头像
            __weak UIImageView * weakImageView = imageView; // 获取头像
            XMPPJID *jid = [XMPPJID jidWithString:content];
            [[HYXMPPManager sharedInstance] getAvatarFromJID:jid avatarBlock:^(NSData *avatar) {
                UIImage * image = nil;
                if (avatar.length) {
                    image = [UIImage imageWithData:avatar];
                }else{
                    image = [UIImage imageNamed:@"defaultHead"];
                }
                weakImageView.image = image;
            }];
            
            imageView.tag = i+1000;
            [YHGestureHelper addTapGesture:imageView number:1 Target:self Sel:@selector(clickHeaderAction:)];
            
        }else if ([type isEqualToString:@"add"]) {
            imageView.image = [UIImage imageNamed:content];
            label.text = @"";
            [YHGestureHelper addTapGesture:imageView number:1 Target:self Sel:@selector(addMemberAction)];
        }else if([type isEqualToString:@"remove"]){
            imageView.image = [UIImage imageNamed:content];
            label.text = @"";
            [YHGestureHelper addTapGesture:imageView number:1 Target:self Sel:@selector(removeMemberAction)];
        }
    }
    [self layoutSubviews];
}

-(void)refreshGroupInfoView
{
    CGFloat width = self.groupInfoView.frame.size.width;
    CGFloat height = self.groupInfoView.frame.size.height;
    
    UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(20,0,60,42)];
    label1.textColor = COLOR(18,18,18,1);
    label1.font = [UIFont systemFontOfSize:15];
    label1.textAlignment = NSTextAlignmentLeft;
    label1.text = @"群名称";
    [self.groupInfoView addSubview:label1];
    
    UILabel * value1 = [[UILabel alloc] initWithFrame:CGRectMake(width-260-40, 0, 260, 42)];
    value1.textColor = COLOR(108,108,108,1);
    value1.font = [UIFont systemFontOfSize:15];
    value1.textAlignment = NSTextAlignmentRight;
    value1.text = self.model.nickName;
    value1.tag = 111;
    [self.groupInfoView addSubview:value1];
    
    UIImageView * iconImageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_right.png"]];
    iconImageView1.frame = CGRectMake(width -8-13, (42-12)/2, 8, 12);
    [self.groupInfoView addSubview:iconImageView1];
    
    UIButton * btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(0, 0, width, 43);
    btn1.backgroundColor = [UIColor clearColor];
    btn1.tag = 1;
    [btn1 addTarget:self action:@selector(modifyAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.groupInfoView addSubview:btn1];
    
    UIView * lineView= [[UIView alloc] initWithFrame:CGRectMake(0, 43, width, 0.5)];
    lineView.backgroundColor = COLOR(237,237,247,1);
    [self.groupInfoView addSubview:lineView];
    
    UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 43, 100, 42)];
    label2.textColor = COLOR(18,18,18,1);
    label2.font = [UIFont systemFontOfSize:15];
    label2.textAlignment = NSTextAlignmentLeft;
    label2.text = @"群公告";
    [self.groupInfoView addSubview:label2];
    
    UILabel * value2 = [[UILabel alloc] initWithFrame:CGRectMake(100, 45, width-100-35, 30+35)];
    value2.textColor = COLOR(108,108,108,1);
    value2.font = [UIFont systemFontOfSize:14];
    value2.textAlignment = NSTextAlignmentLeft;
    value2.numberOfLines = 0;
    value2.text = self.model.notice;
    value2.tag = 222;
    [self.groupInfoView addSubview:value2];
    
    UIImageView * iconImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_right.png"]];
    iconImageView2.frame = CGRectMake(width -8-13, 43+(65-12)/2, 8, 12);
    [self.groupInfoView addSubview:iconImageView2];
    
    UIButton * btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.backgroundColor = [UIColor clearColor];
    btn2.frame = CGRectMake(0, 43, width, height-43);
    btn2.tag = 2;
    [btn2 addTarget:self action:@selector(modifyAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.groupInfoView addSubview:btn2];
}

-(void)refreshClearView
{
    UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 300, self.clearView.frame.size.height)];
    label2.textColor = COLOR(18,18,18,1);
    label2.font = [UIFont systemFontOfSize:15];
    label2.textAlignment = NSTextAlignmentLeft;
    label2.text = @"清空聊天记录";
    [self.clearView addSubview:label2];
}

#pragma mark -

-(UIScrollView *)topScrollView
{
    if (!_topScrollView) {
        _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
        _topScrollView.backgroundColor = [UIColor whiteColor];
        _topScrollView.layer.borderColor= COLOR(237, 237, 247, 1).CGColor;
        _topScrollView.layer.borderWidth = 0.5;
    }
    return _topScrollView;
}

-(UIView *)groupMemberView
{
    if (!_groupMemberView) {
        _groupMemberView = [[UIView alloc] initWithFrame:CGRectZero];
        _groupMemberView.backgroundColor = [UIColor whiteColor];
    }
    return _groupMemberView;
}

-(UIView *)groupInfoView
{
    if (!_groupInfoView) {
        _groupInfoView = [[UIView alloc] initWithFrame:CGRectZero];
        _groupInfoView.backgroundColor = [UIColor whiteColor];
        _groupInfoView.layer.borderColor= COLOR(237, 237, 247, 1).CGColor;
        _groupInfoView.layer.borderWidth = 0.5;
    }
    return _groupInfoView;
}

-(UIView *)clearView
{
    if (!_clearView) {
        _clearView = [[UIView alloc] initWithFrame:CGRectZero];
        _clearView.backgroundColor = [UIColor whiteColor];
        _clearView.layer.borderColor= COLOR(237, 237, 247, 1).CGColor;
        _clearView.layer.borderWidth = 0.5;
        
        [YHGestureHelper addTapGesture:_clearView number:1 Target:self Sel:@selector(clearAction)];
    }
    return _clearView;
}

-(UIButton *)delAndExitBtn
{
    if (!_delAndExitBtn) {
        _delAndExitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_delAndExitBtn setTitle:@"删除并退出" forState:UIControlStateNormal];
        [_delAndExitBtn setBackgroundColor:APP_MAIN_COLOR];
        [_delAndExitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_delAndExitBtn.layer setCornerRadius:9.0];
        [_delAndExitBtn addTarget:self action:@selector(delAndExitAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _delAndExitBtn;
}

-(NSMutableArray *)groupMembers
{
    if (!_groupMembers) {
        _groupMembers = [NSMutableArray array];
    }
    return _groupMembers;
}
-(NSMutableArray *)membersImages
{
    if (!_membersImages) {
        _membersImages = [NSMutableArray array];
    }
    return _membersImages;
}

#pragma mark -
//生产群头像
-(void)generateHeadImage
{
    [self.membersImages removeAllObjects];
    for (UIView * subView in self.groupMemberView.subviews) {
        if ([subView isKindOfClass:[UIImageView class]] && subView.tag >= 1000) {
            UIImage * image= ((UIImageView *)subView).image;
            if (image) {
                [self.membersImages addObject:image];
            }
        }
    }
    
    UIImage *img = [[APGroupImageUtil shared] mergeWithImageArray:self.membersImages size:CGSizeMake(100, 100) backgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]];
    if (img) {
        
        [[HYLoginInfo sharedInstance] saveGroupImage:img withJidU:self.model.jid.user];
        
        NSData *data = UIImageJPEGRepresentation(img, 0.01);
        self.vCard.photo = data;
        
//        XMPPJID * jid = [self.model.jid copy];
//        XMPPvCardTemp *vCardt = [self.vCard copy];
//        //上传群头像
//        [[HYXMPPManager sharedInstance] updatevCardFromJID:jid vCard:vCardt successBlock:^(BOOL success) {
//            NSLog(@"更新群头像+%d",success);
//        }];
    }
}

#pragma mark -

-(void)delAndExitAction
{
    YHWeakifySelf;
    [HYUtils showLoadingMsg:@"加载中"];
    if (self.isSelfOwn) {
        // 删除聊天室
        [[HYXMPPGroupManager sharedInstance] destroyGroupWithGroupJID:self.model.jid success:^(BOOL success) {
            if (success) {
                [HYUtils clearWaitingMsg];
                [yh_weak_self clearAction];
                [yh_weak_self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [HYUtils alertWithErrorMsg:@"操作失败，请重试"];
            }
        }];
    }else{
        // 退出聊天室
        HYContactsModel *model = [[HYContactsModel alloc] init];
        model.jid = [HYXMPPManager sharedInstance].myJID;
        [[HYXMPPGroupManager sharedInstance] leaveMembers:@[model] inGroupJID:self.model.jid success:^(BOOL success) {
            if (success) {
                [HYUtils clearWaitingMsg];
                [yh_weak_self clearAction];
                [yh_weak_self.navigationController popToRootViewControllerAnimated:YES];
            }else{
                [HYUtils alertWithErrorMsg:@"操作失败，请重试"];
            }
        }];
    }
}

-(void)clearAction
{
    [HYUtils showLoadingMsg:nil];
    HYRecentChatModel *model = [[HYRecentChatModel alloc] init];
    model.jid = self.model.jid;
    [[HYDatabaseHandler sharedInstance] deleteRecentChatModel:model]; // 删除最近联系人中的数据
    [[HYDatabaseHandler sharedInstance] deleteChatMessageWithGroupJid:model.jid];// 删除聊天记录
    [HYUtils performSelector:@selector(alertWithNormalMsg:) withObject:@"删除成功" afterDelay:0.5f];
}

-(void)addMemberAction
{
    YHGroupInviteViewController *inviteVC = [[YHGroupInviteViewController alloc] init];
    inviteVC.groupJid = self.model.jid;
    inviteVC.selectedArray = self.groupMembers;
    inviteVC.vCard = self.vCard;
    inviteVC.hidesBottomBarWhenPushed = YES; // 隐藏tabBar
    YHWeakifySelf;
    [inviteVC setGroupMembersBlock:^(NSArray *groupMembers) {
        [yh_weak_self refreshData];
    }];
    [self.navigationController pushViewController:inviteVC animated:YES];
}

-(void)removeMemberAction
{
    YHGroupInviteViewController *inviteVC = [[YHGroupInviteViewController alloc] init];
    inviteVC.groupJid = self.model.jid;
    inviteVC.selectedArray = self.groupMembers;
    inviteVC.isRemove = YES;
    inviteVC.hidesBottomBarWhenPushed = YES; // 隐藏tabBar
    YHWeakifySelf;
    [inviteVC setGroupMembersBlock:^(NSArray *groupMembers) {
        [yh_weak_self refreshData];
    }];
    [self.navigationController pushViewController:inviteVC animated:YES];
}

-(void)modifyAction:(UIButton *)btn
{
    if (self.isSelfOwn) {
        if (btn.tag == 1) {
            //修改群名称
            HYCommonSetViewController * vc = [[HYCommonSetViewController alloc] initWithLabel:@"群名称" finishBlock:^(NSString *resultValue) {
                
                [self modifyGroupName:resultValue];
            }];
            UILabel * label = [self.groupInfoView viewWithTag:111];
            vc.valueTextView.text = label.text;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            HYCommonSetViewController * vc = [[HYCommonSetViewController alloc] initWithLabel:@"群公告" finishBlock:^(NSString *resultValue) {
                
                [self modifyGroupDesc:resultValue];
            }];
            UILabel * label = [self.groupInfoView viewWithTag:222];
            vc.valueTextView.text = label.text;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else{
        NSString * message = nil;
        NSString * title = nil;
        if (btn.tag == 1) {
            title = @"群名称";
            message = self.model.nickName;
        }else{
            title = @"群公告";
            UILabel * label = [self.groupInfoView viewWithTag:222];
            message = label.text;
        }
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
-(void)modifyGroupName:(NSString *)newName
{
    UILabel * label = [self.groupInfoView viewWithTag:111];
    if ([label.text isEqualToString:newName]) {
        return;
    }
    
    YHWeakifySelf;
    [[HYXMPPGroupManager sharedInstance] modifyGroupName:newName withGroupJID:self.model.jid success:^(BOOL success) {
        YHStrongifySelf;
        self.isModify = YES;
        if (success) {
            UILabel * label = [self.groupInfoView viewWithTag:111];
            label.text = newName;
            self.model.nickName = newName;
            if (self.groupModifyBlock) {
                self.groupModifyBlock(YES);
            }
            if ([self.model isKindOfClass:[HYRecentChatModel class]]) {
                HYRecentChatModel *chatModel=(HYRecentChatModel *)self.model;
                [[HYDatabaseHandler sharedInstance] updateRecentChatModel:chatModel];
            }
            
        }else{
            [HYUtils alertWithErrorMsg:@"保存失败"];
        }
    }];
}

-(void)modifyGroupDesc:(NSString *)newDesc
{
    UILabel * label = [self.groupInfoView viewWithTag:222];
    if ([label.text isEqualToString:newDesc]) {
        return;
    }
    
    YHWeakifySelf;
    [[HYXMPPGroupManager sharedInstance] modifyGroupNotice:newDesc withGroupJID:self.model.jid success:^(BOOL success) {
        YHStrongifySelf;
        self.isModify = YES;
        if (success) {
            UILabel * label2 = [self.groupInfoView viewWithTag:222];
            label2.text = newDesc;
            self.isModify = YES;
            if (self.groupModifyBlock) {
                self.groupModifyBlock(YES);
            }
        }else{
            [HYUtils alertWithErrorMsg:@"保存失败"];
        }
    }];
}

// 点击头像
-(void)clickHeaderAction:(UITapGestureRecognizer *)gestureRecognizer
{
    NSInteger tag = gestureRecognizer.view.tag - 1000;
    if (tag >=0 && tag < self.groupMembers.count) {
        HYContactsModel * member = [self.groupMembers objectAtIndex:tag];
        [self didClickHeaderWithJid:member.jid];
    }
}
-(void)didClickHeaderWithJid:(XMPPJID *)jid
{
    HYUservCardViewController *userVC = [[HYUservCardViewController alloc] init];
    userVC.userJid = jid;
    userVC.canNoChat = YES;
    [self.navigationController pushViewController:userVC animated:YES];
}

-(void)back:(id)sender
{
    if (self.isModify) {
        if (self.groupModifyBlock) {
            self.groupModifyBlock(YES);
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

@end
